package co.bugu.es8.infra;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;

/**
 * ipguard 加解密
 * @Date: 2023/8/4 23:49
 * @Description:
 */
public class IpGuardDecrypt {
    public static void main(String[] args) throws IOException {

        String fromPath="f://ipg/【信息化中心】2024年年度集团总部部长级及以上人员绩效考核结果.xlsx";
        String toPath="f://ipg/【信息化中心】2024年年度集团总部部长级及以上人员绩效考核结果-无密.xlsx";


        if (args.length == 3) {
            decryptUrlNew = args[0];
            fromPath = args[1];
            toPath = args[2];
        }

        File file = new File(fromPath);

        InputStream in = decryptByFile(file);
        FileOutputStream out = new FileOutputStream(toPath);
        int data;
        while ((data = in.read()) != -1) {
            out.write(data);
            out.flush();
        }
        in.close();
        System.out.println("=======");
    }


    private static String appId = "1000057741";

    private static String appKey = "XMTXs90303z78388";
    /** 解密地址 */
    private static String decryptUrlNew = "http://10.249.0.108:8081/lbxdecrypt/ecrypt/decrypt";


    public static InputStream decryptByFile(File file) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String fileName = file.getName();
        InputStream content = null;
        HttpEntity entity = null;

        try {
            HttpPost httpPost = new HttpPost(decryptUrlNew);
            RequestConfig.Builder customReqConf = RequestConfig.custom();
            httpPost.setConfig(customReqConf.build());
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            builder.setCharset(Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addBinaryBody("file", new FileInputStream(file), ContentType.create(ContentType.MULTIPART_FORM_DATA.getMimeType(), "utf-8"), fileName);
            SortedMap<String, Object> parameters = new TreeMap();
            parameters.put("app_id", appId);
            parameters.put("time_stamp", System.currentTimeMillis() / 1000L);
            parameters.put("nonce_str", UUID.randomUUID());
            String sign = verify((SortedMap)parameters);
            parameters.put("filename", fileName);
            parameters.put("type", "1");
            parameters.put("decrypt_type", "1");
            parameters.put("user_id", "000001");
            parameters.put("desc", "");
            parameters.put("sign", sign);
            Iterator var10 = parameters.entrySet().iterator();

            while(var10.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry)var10.next();
                builder.addTextBody(entry.getKey(), "" + entry.getValue(), ContentType.create(ContentType.MULTIPART_FORM_DATA.getMimeType(), "utf-8"));
            }

            entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == 200) {
                content = responseEntity.getContent();
            }

            return content;
        } catch (Exception e) {
            System.out.println("加解密接口发生报错 -> " + fileName + ":" + e.getMessage());
            e.printStackTrace();

            try {
                if (content != null) {
                    content.close();
                }

                if (entity != null) {
                    EntityUtils.consume(entity);
                }
            } catch (IOException var12) {
                System.out.println("加解密接口关闭流发生报错 -> " + fileName + ":" + var12.getMessage());
                var12.printStackTrace();
            }

            return null;
        }
    }

    private static String verify(SortedMap<String, Object> parameters) throws Exception {
        String sign = "";
        StringBuffer sb = new StringBuffer();
        String sign2 = null;
        Set es = parameters.entrySet();
        Iterator it = es.iterator();

        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"app_key".equals(k)) {
                String value = URLEncoder.encode(v.toString(), "UTF-8");
                sb.append(k + "=" + value + "&");
            }
        }

        sb.append("app_key=" + appKey);

        sign2 = MD5Util.getMD5(sb.toString()).toUpperCase();

//        sign2 = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
        return sign2;
    }
}
